package com.shell.customer.accreditation.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.shell.bee.base.annotation.Logging;
import com.shell.bee.base.utils.SpringContextUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.entity.mvc.RetMsg;
import com.shell.bee.persistence.model.PageLimit;
import com.shell.customer.accreditation.service.AccreditationService;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.accreditation.vo.AuthenticatingCusVo;
import com.shell.customer.accreditation.vo.CusOptVo;
import com.shell.customer.accreditation.vo.UserVo;
import com.shell.customer.base.service.CusCheckService;
import com.shell.customer.base.service.CusOptService;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.group.service.CusGrpService;
import com.shell.customer.po.CusAcct;
import com.shell.customer.po.CusGrp;
import com.shell.customer.po.CusOpt;
import com.shell.customer.util.CustomerUtil;
import com.shell.feign.PubUserFeign;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.governor.user.po.PubUser;
import com.shell.governor.user.vo.PubUserVo;
import com.shell.sms.SMSResponse;
import com.timevale.esign.sdk.tech.bean.result.Result;

@RestController
public class AccreditationController {
	@Autowired
	private CusRecService customerCService;
	@Autowired
	private AccreditationService accreditationService;
	@Autowired
	private CusOptService pubCusOptService;
	@Autowired
	private PubUserFeign pubUserFeign;
	@Autowired
	private CusCheckService cusCheckService;
	@Autowired
	private CusGrpService cusGrpService;

	@RequestMapping
	@Logging(module = "��������", methods = "��������-������������")
	public AccreditationVo getCustomerInfo() {
		String cusId = CommonDataUtil.getCurEntId();

		AccreditationVo vo = this.accreditationService.getCustomerInfo(cusId);

		List<PubUserVo> users = this.pubUserFeign.selectAllUserForEnt(cusId);
		for (PubUserVo user : users) {
			UserVo userVo = new UserVo(user);
			if (vo.getCustomerC().getContactorId().equals(user.getUserId())) {
				vo.setAdministrator(userVo);
			}
		}
		return vo;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-������������")
	public RetMsg saveAccreditationData(@RequestBody AccreditationVo accreditationVo) {
		this.accreditationService.saveAccreditationData(accreditationVo);
		return new RetMsg("success", true, "����������������������");
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������������")
	public List<AuthenticatingCusVo> getAuthenticatingCus(PageLimit limit, String grpIds,
			@RequestParam(name = "cusState") String cusState, @RequestParam(name = "cusType") String cusType,
			@RequestParam(name = "cusName") String cusName) {
		String[] grpIdArr = null;
		if (StringUtil.notEmpty(grpIds)) {
			grpIdArr = grpIds.split(",");
		} else {
			List<CusGrp> grps = this.cusGrpService.selectCusGroupByTagCode(CommonDataUtil.getCurEntId(),
					"GROUP_FIRST_TRIAL");
			if (grps != null) {
				List<String> grpArr = new ArrayList();
				for (CusGrp grp : grps) {
					grpArr.add(grp.getGrpId());
				}
				grpIdArr = (String[]) grpArr.toArray(new String[grpArr.size()]);
			}
		}
		return this.customerCService.getAuthenticatingCus(limit, grpIdArr, cusState, cusType, cusName);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������������")
	public List<AuthenticatingCusVo> getLastTrialCus(PageLimit limit, String grpIds,
			@RequestParam(name = "cusState") String cusState, @RequestParam(name = "cusType") String cusType,
			@RequestParam(name = "cusName") String cusName) {
		String[] grpIdArr = null;
		if (StringUtil.notEmpty(grpIds)) {
			grpIdArr = grpIds.split(",");
		} else {
			List<CusGrp> grps = this.cusGrpService.selectCusGroupByTagCode(CommonDataUtil.getCurEntId(),
					"GROUP_LAST_TRIAL");
			if (grps != null) {
				List<String> grpArr = new ArrayList();
				for (CusGrp grp : grps) {
					grpArr.add(grp.getGrpId());
				}
				grpIdArr = (String[]) grpArr.toArray(new String[grpArr.size()]);
			}
		}
		return this.customerCService.getLastTrialCus(limit, grpIdArr, cusState, cusType, cusName);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-������������������")
	public AccreditationVo getAccreditationData(@RequestParam(name = "contactorId") String contactorId,
			@RequestParam(name = "cusId") String cusId) {
		AccreditationVo accreditationVo = this.accreditationService.getCustomerInfo(cusId);

		accreditationVo.setShowContract("on".equals(SpringContextUtil.getProperty("contract.switch")));

		List<PubUserVo> users = this.pubUserFeign.selectAllUserForEnt(cusId);

		List<UserVo> operators = new ArrayList();
		for (PubUser user : users) {
			UserVo userVo = new UserVo(user);
			if (!contactorId.equals(user.getUserId())) {
				operators.add(userVo);
			} else {
				accreditationVo.setAdministrator(userVo);
			}
		}
		accreditationVo.setOperators(operators);

		return accreditationVo;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-��������������������")
	public CusOpt getLatestOpt(@RequestParam(name = "cusId") String cusId) {
		return this.pubCusOptService.getLatestOptReadOnly(cusId);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-��������")
	public RetMsg firstTrialPass(CusOptVo cusOpt, BigDecimal crediLine) {
		return this.accreditationService.firstTrialPass(cusOpt, crediLine);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-��������")
	public RetMsg lastTrialPass(CusOptVo cusOpt) {
		return this.accreditationService.lastTrialPass(cusOpt);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-��������")
	public RetMsg lastTrialReject(CusOpt cusOpt) {
		this.accreditationService.lastTrialReject(cusOpt);
		return new RetMsg("success", true, "������������");
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-��������")
	public RetMsg firstTrialReject(CusOpt cusOpt) {
		this.accreditationService.firstTrialReject(cusOpt);
		return new RetMsg("success", true, "������������������������");
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������-������������")
	public List<CusOptVo> getPreviousOpts(@RequestParam(name = "cusId") String cusId) {
		return this.pubCusOptService.getPreviousOpts(cusId);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������������������")
	public PubUser checkUserExist(@RequestParam(name = "phoneNo", required = false) String phoneNo,
			@RequestParam(name = "userId", required = false) String userId,
			@RequestParam(name = "excludeCurUser", required = false) Boolean excludeCurUser) throws Exception {
		PubUser pubUser = new PubUser();
		pubUser.setPhoneNo(phoneNo);
		if (StringUtil.notEmpty(userId)) {
			pubUser.setUserId(userId);
		}
		List<PubUserVo> users = this.pubUserFeign.selectByEntity(pubUser);

		PubUser result = null;
		if (users == null) {
			return result;
		}
		if (users.size() > 0) {
			if (users.size() == 1) {
				if ((null != excludeCurUser) && (!excludeCurUser.booleanValue())
						&& (null != CommonDataUtil.getCurUser())
						&& (CommonDataUtil.getCurUser().getUserId().equals(((PubUserVo) users.get(0)).getUserId()))) {
					result = null;
				} else if ((StringUtil.notEmpty(userId)) && (userId.equals(((PubUserVo) users.get(0)).getUserId()))) {
					result = null;
				} else {
					result = (PubUser) users.get(0);
				}
			} else {
				result = (PubUser) users.get(0);
			}
		}
		return result;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������������")
	public boolean checkInviteCode(String inviteCode) {
		return this.cusCheckService.checkInviteCode(inviteCode);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "����������������")
	public Map<String, String> genAccreditationFiles(@RequestBody AccreditationVo accreditationVo) {
		return this.accreditationService.genAccreditationFiles(accreditationVo);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������������")
	public Map<String, String> genCusAuthFile(@RequestBody AccreditationVo accreditationVo) {
		Map<String, String> map = new HashMap();
		String cusAuthFileId = this.accreditationService.genCusAuthFile(accreditationVo);
		map.put("cusAuthFileId", cusAuthFileId);
		return map;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "e����������������")
	public RetMsg signAccreditionFile(@RequestBody AccreditationVo accreditationVo) {
		if (CustomerUtil.onEsign()) {
			Result result = this.accreditationService.esignAccreditionFile(accreditationVo);
			if (result.getErrCode() != 0) {
				return new RetMsg("error", true, "����������������������" + result.getMsg());
			}
		} else {
			SMSResponse response = this.accreditationService.cfcaAccreditionFile(accreditationVo);
			if (!response.isSuccess()) {
				return new RetMsg("error", true, "����������������������" + response.getErrMsg());
			}
		}
		return new RetMsg("success", false, "����������������������������");
	}

	@RequestMapping
	@Logging(module = "��������", methods = "e����������������")
	public RetMsg esignPayAmountAuth(BigDecimal amount) {
		return this.accreditationService.esignPayAmountAuth(amount);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "����������������")
	public CusAcct getCusAcct() {
		String entId = CommonDataUtil.getCurEntId();
		CusAcct cusAcct = this.accreditationService.getCusAcct(entId);
		cusAcct.setCusId(entId);
		return cusAcct;
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������")
	public RetMsg saveCusAcct(CusAcct cusAcct) {
		return this.accreditationService.saveCusAcct(cusAcct);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "e����������������")
	public RetMsg esignAuthEntInfo(@RequestBody AccreditationVo accreditationVo) {
		String msg;
		try {
			msg = this.accreditationService.esignAuthEntInfo(accreditationVo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
		}
		if (StringUtil.emptyAndNull(msg)) {
			return new RetMsg("success", true, "����������������");
		}
		return new RetMsg("error", false, msg);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������")
	public RetMsg authEntInfo(@RequestBody AccreditationVo accreditationVo) {
		String msg = "����������������";
		try {
			if (CustomerUtil.onEsign()) {
				msg = this.accreditationService.esignAuthEntInfo(accreditationVo);
			} else if (CustomerUtil.onCfca()) {
				msg = this.accreditationService.cfcaAuthEntInfo(accreditationVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
		}
		if (StringUtil.emptyAndNull(msg)) {
			return new RetMsg("success", true, "����������������");
		}
		return new RetMsg("error", false, msg);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������������")
	public RetMsg authAdministrator(@RequestBody AccreditationVo accreditationVo) {
		String msg = "������������������";
		try {
			if (CustomerUtil.onEsign()) {
				msg = this.accreditationService.esignAuthAdministrator(accreditationVo);
			} else if (CustomerUtil.onCfca()) {
				msg = this.accreditationService.cfcaAuthAdministrator(accreditationVo, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
		}
		if (StringUtil.emptyAndNull(msg)) {
			return new RetMsg("success", true, "������������������");
		}
		return new RetMsg("error", false, msg);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������������")
	public RetMsg authAuthOperators(@RequestBody AccreditationVo accreditationVo) {
		String msg = "������������������";
		try {
			if (CustomerUtil.onEsign()) {
				msg = this.accreditationService.esignAuthOperators(accreditationVo);
			} else if (CustomerUtil.onCfca()) {
				msg = this.accreditationService.cfcaAuthAdministrator(accreditationVo, true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
		}
		if (StringUtil.emptyAndNull(msg)) {
			return new RetMsg("success", true, "������������������");
		}
		return new RetMsg("error", false, msg);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "������������")
	public RetMsg payAmountVerification(BigDecimal amount) {
		return this.accreditationService.payAmountVerification(amount);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "e����������������������")
	public RetMsg esignAuthAdministrator(@RequestBody AccreditationVo accreditationVo) {
		String msg;
		try {
			msg = this.accreditationService.esignAuthAdministrator(accreditationVo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
		}
		if (StringUtil.emptyAndNull(msg)) {
			return new RetMsg("success", true, "������������������");
		}
		return new RetMsg("error", false, msg);
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������������")
	public RetMsg esignAuthOperators(@RequestBody AccreditationVo accreditationVo) {
		String msg;
		try {
			msg = this.accreditationService.esignAuthOperators(accreditationVo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
		}
		if (StringUtil.emptyAndNull(msg)) {
			return new RetMsg("success", true, "������������������");
		}
		return new RetMsg("error", false, msg);
	}
}